var http = require('../../script/api.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    PAY_MONEY: 0,
    USER_ID: '',
    paymentParams: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const {
      id,
      money
    } = options;
    this.setData({
      USER_ID: id,
      PAY_MONEY: money
    });
   this.CreateOrder();
  },
  // 调用后端API创建支付订单
  CreateOrder() {
    wx.showLoading({
      title: '订单创建中..',
      mask: true
    })
    const params = {
      data: {
        USER_ID: this.data.USER_ID,
        PAY_MONEY: this.data.PAY_MONEY
      }
    };
    http.CreateOrder(params).then(res => {
      if (res.code === 200) {
        wx.hideLoading();
        // this.wechatPay(res.data.Data);
        this.setData({
          paymentParams: res.data.Data
        })
      } else {
        wx.showToast({
          title: '订单创建失败',
          icon: 'none',
          duration: 2000,
          success: function () {
            setTimeout(() => {
              wx.navigateBack();
            }, 2000)
          }
        });
      }
    }).catch(() => {
      setTimeout(() => {
        wx.navigateBack();
      }, 2000)
    })
  },
  wechatPay(paymentParams) {
    wx.requestPayment({
      // "timeStamp": "1414561699",
      // "nonceStr": "5K8264ILTKCH16CQ2502SI8ZNMTM67VS",
      // "package": "prepay_id=wx201410272009395522657a690389285100",
      // "signType": "RSA",
      // "paySign": "oR9d8PuhnIc+YZ8cBHFCwfgpaK9gd7vaRvkYD7rthRAZ\/X+QBhcCYL21N7cHCTUxbQ+EAt6Uy+lwSN22f5YZvI45MLko8Pfso0jm46v5hqcVwrk6uddkGuT+Cdvu4WBqDzaDjnNa5UK3GfE1Wfl2gHxIIY5lLdUgWFts17D4WuolLLkiFZV+JSHMvH7eaLdT9N5GBovBwu5yYKUR7skR8Fu+LozcSqQixnlEZUfyE55feLOQTUYzLmR9pNtPbPsu6WVhbNHMS3Ss2+AehHvz+n64GDmXxbX++IOBvm2olHu3PsOUGRwhudhVf7UcGcunXt8cqNjKNqZLhLw4jq\/xDg==",
      timeStamp: paymentParams.timeStamp,
      nonceStr: paymentParams.nonceStr,
      package: paymentParams.package,
      signType: paymentParams.signType,
      paySign: paymentParams.paySign,
      success: (res) => {
        wx.showToast({
          title: '支付成功'
        });
        // 支付成功后，可以跳转回原页面或成功页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      },
      fail: (err) => {
        wx.showToast({
          title: '支付取消或失败',
          icon: 'none'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})